package com.wangp.safeCommit.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangp.safeCommit.dto.HazardDateQueryRequestDTO;
import com.wangp.safeCommit.dto.HazardDateQueryResponseDTO;
import com.wangp.safeCommit.entity.HazardDataEntity;
import com.wangp.safeCommit.entity.HazardEntity;
import com.wangp.safeCommit.mapper.HazardDataMapper;
import com.wangp.safeCommit.service.IHazardDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 危险源数据 服务实现类
 * </p>
 *
 * @author zhangliang
 * @since 2024-12-17
 */
@Service
public class HazardDataServiceImpl extends ServiceImpl<HazardDataMapper, HazardDataEntity> implements IHazardDataService {

    @Autowired
    private   HazardDataMapper hazardDataMapper;
    @Override
    public HazardDateQueryResponseDTO queryPage(final HazardDateQueryRequestDTO hazardDTO)  {

      this.validate(hazardDTO);
        //分页
        int current = hazardDTO.getCurrent();
        int size = Math.min(hazardDTO.getSize(),500);
        int offset = (current - 1) * size;

        //时间赋值
        String time = hazardDTO.getTime();
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime=null;
        Date endTime=null;
        try {
             startTime= dateTimeFormat.parse(time + " 00:00:00");
             endTime=dateTimeFormat.parse(time + " 23:59:59");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // 分页数据
        List<HazardEntity> hazardEntityList  = hazardDataMapper.findHazardPageData(hazardDTO, startTime, endTime, offset, size);

        // 查询总记录数
        long count = hazardDataMapper.findHazardPageDataTotal(hazardDTO, startTime, endTime);

        // 封装分页数据
        HazardDateQueryResponseDTO result = new HazardDateQueryResponseDTO();
        result.setData(hazardEntityList);
        result.setCurrent(current);
        result.setSize(size);
        result.setTotal(count);
        result.setTime(time);
        return result;
    }

    private void validate(final HazardDateQueryRequestDTO hazardDTO) {

        if (hazardDTO.getTime() == null || hazardDTO.getTime().isEmpty()) {
            throw new IllegalArgumentException("时间不能为空,正确格式应为: yyyy-MM-dd");
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setLenient(false);

        // 尝试解析日期，如果失败则抛出异常
        try {
            formatter.parse(hazardDTO.getTime());
        } catch (ParseException e) {
            throw new IllegalArgumentException("日期格式有误，正确格式应为: yyyy-MM-dd", e);
        }
    }


}
